package com.cykj.pos.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class PublicUtil {
    public static File[] getCurFilesList(String filepath){
        File file = new File(filepath);

        //  File[] listfiles = file.listFiles();
        File[] listfiles = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.isFile()){
                    return true;
                }else{
                    return false;
                }
            }
        });

        return listfiles;
    }

    public static Map<String,String> generateMap(String json){
        org.json.JSONObject jsonObject = new org.json.JSONObject(json);
        HashMap<String, String> map = new HashMap<String, String>();
        Iterator it = jsonObject.keys();
        while(it.hasNext()){
            String key = String.valueOf(it.next().toString());
            String value = jsonObject.get(key).toString();
            map.put(key, value);
        }
        return map;
    }


    public static String sendSms(String url, JSONObject content) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("content-Type", "application/json");
            //创建请求内容
            StringEntity entity = new StringEntity(content.toString(), "utf-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

}
